# Create your views here.
    
from django.http import Http404
from django.http import HttpResponse
from django.template import Context, loader
from nanaze.blog.models import Entry, Comment
from django.http import HttpResponseRedirect
from django.utils import feedgenerator
from django.template.defaultfilters import linebreaks

from datetime import datetime

SITE_BASE = "http://www.nanaze.com"

def index(request):
    return make_response(
	Entry.get_published().order_by("-pub_date")[:5])

def rss(request):
    return make_feed(feedgenerator.Rss201rev2Feed)

def atom(request):
    return make_feed(feedgenerator.Atom1Feed)

def make_feed(constructor):
    feed = constructor(
	title=u"nanaze.com",
	link=SITE_BASE,
	description=u"Writings on technology, among other things.",
	language=u"en")

    entries = Entry.get_published().order_by("-pub_date")[:10]

    for entry in entries:
	text = linebreaks(entry.text)
	feed.add_item(title=entry.title,
	              author_name="Nathan Naze",
		      link=(SITE_BASE + entry.url()),
		      description=text,
		      pubdate=entry.pub_date)

    return HttpResponse(feed.writeString('utf-8'))

def get_entries(year=None, month=None, day=None, urlname=None):
    filters = {}
    if year: filters['pub_date__year'] = int(year)
    if month: filters['pub_date__month'] = int(month)
    if day: filters['pub_date__day'] = int(day)
    return Entry.get_published().filter(**filters)
    
def entry_filter(request, year=None, month=None, day=None, urlname=None,
		 show_comments=False, check_for_comment=False):

    entries = get_entries(year, month, day)

    def matches(entry):
	return entry.urlname() == urlname

    if urlname:
	entries = filter(matches, entries)

    if request.method == "POST" and len(entries) == 1:
	add_comment(entries[0], 
		    request.POST['name'],
		    request.POST['url'],
		    request.POST['text'])

    return make_response(entries, show_comments)

def static_template(request, template):
    return general_response(template=template)

def make_response(entries, show_comments=False):

    if len(entries) == 0:
        raise Http404

    for e in entries:
	if show_comments:
	    comments = e.comment_set.filter(entry=e)
	    if len(comments) > 0:
		e.comments = comments
	else:
	    e.comment_count = Comment.objects.filter(entry=e.id).count()
    
    return general_response({'entries' : entries,
			     'show_comments' : show_comments})

def general_response(context={}, template="entry.html"):
    t = loader.get_template(template)
    return HttpResponse(t.render(Context(context)))

def add_comment(entry, name, url, text):
    comment = Comment(name=name, url=url, text=text, entry=entry)
    comment.save()
    return HttpResponseRedirect(entry.url())
